package sssex.editors;


import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.MultiPageEditorPart;

//import com.genuitec.eclipse.webdesigner3.editors.WebDesignerMultiPageEditor;

/**
 * An example showing how to create a multi-page editor.
 * This example has 3 pages:
 * <ul>
 * <li>page 0 contains a nested text editor.
 * <li>page 1 allows you to change the font used in page 2
 * <li>page 2 shows the words in page 0 in sorted order
 * <li>http://www.ibm.com/developerworks/cn/opensource/tutorials/os-eclipse-plugin-guide/
 * http://www.ibm.com/developerworks/cn/opensource/os-cn-eclipse-udrd/index.html
 * http://blog.csdn.net/davidhsing/article/details/6943696
 * </ul> 
 */

public class MultiPageEditor extends MultiPageEditorPart implements IResourceChangeListener{

	/** The text editor used in page 0. */
	//private WebDesignerMultiPageEditor editor;
	
	/** The text editor used in page 0. */
	private TextEditor editor;

	
	public static Map<String,MultiPageEditor> multiPageEditorMap = new HashMap<String,MultiPageEditor>();
	
	//public IDocument doc;
	
	/** 
	 * Creates a multi-page editor example.
	 */
	public MultiPageEditor() {
		super(); 
		ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
	}
	
	public void setPageText1(int index, String title){
		setPageText(index,title);
	}
	
	/**
	 * Creates page 0 of the multi-page editor,
	 * which contains a text editor.
	 */
	void createPage0() {
		try {
			editor = new TextEditor();
			int index = addPage(editor, getEditorInput());
			setPageText(index, editor.getTitle());
			
		} catch (PartInitException e) {
			ErrorDialog.openError(
				getSite().getShell(),
				"Error creating nested text editor",
				null,
				e.getStatus());
		}
//		try { 
//			editor = new com.genuitec.eclipse.webdesigner3.editors.WebDesignerMultiPageEditor();
			// editor.removePage(0);
//			System.out.println(editor.getPartName());
//			org.eclipse.text.undo.DocumentUndoManager df = null;
//			int index = addPage(editor, getEditorInput() );
//			doc = editor.getSourceEditor().getDocumentProvider().getDocument(editor.getEditorInput());
//			setPageText(index, " 编辑器 ");
//			IFileEditorInput input = (IFileEditorInput)getEditorInput();
//			if(input instanceof IFileEditorInput){ 
//				IFile file = ((IFileEditorInput)input).getFile();
//				IPath path = file.getFullPath();
//				String editFile = path.toString();
//				multiPageEditorMap.put(editFile,this);
//			}
//		} catch (PartInitException e) {
//			ErrorDialog.openError(
//				getSite().getShell(),
//				"Error creating nested text editor",
//				null,
//				e.getStatus());
//		}
	}
	
	
	/**
	 * Creates page 1 of the multi-page editor,
	 * which allows you to change the font used in page 2.
	 */
	void createPage1() {
		/* */
		Composite composite = new Composite(getContainer(), SWT.NONE);
		FillLayout layout = new FillLayout();
		composite.setLayout(layout);

		IFileEditorInput input = (IFileEditorInput)getEditorInput();
		int index = addPage(composite);
		setPageText(index, "Preview");
		
		Browser browser1 = new Browser(composite, SWT.NONE);
		if(input instanceof IFileEditorInput){ 
			IFile file = ((IFileEditorInput)input).getFile();
			browser1.setUrl(file.getLocation().makeAbsolute().toFile().getAbsolutePath());
		}
		
	}
	
	/**
	 * Creates page 1 of the multi-page editor,
	 * which allows you to change the font used in page 2.
	 * @throws PartInitException 
	 */
	void createPage2(){
		// System.out.println("getEditorInput:"+getEditorInput());
		/* */
		Composite composite = new Composite(getContainer(), SWT.NONE);
		FillLayout layout = new FillLayout();
		composite.setLayout(layout);
		int index = addPage(composite);
		setPageText(index, "Design");
		Browser browser1 = new Browser(composite, SWT.NONE);
		//if(input instanceof IFileEditorInput){
			//IFile file = ((IFileEditorInput)input).getFile(); 
			//browser1.setText("<html><body>ssssss</body>< /html>");
		// System.out.println(sssex.Activator.plugin_path);
		// browser1.setUrl("file:///"+sssex.Activator.plugin_path+"kindeditor-4.1.10/examples/default.html");
		IFileEditorInput input = (IFileEditorInput)getEditorInput();
		String editFile = "";
		if(input instanceof IFileEditorInput){ 
			IFile file = ((IFileEditorInput)input).getFile();
			this.setPartName(file.getName());
			IPath path = file.getFullPath();
			this.setTitleToolTip(path.toString());
			editFile = path.toString();
		}
		try {
			editFile = java.net.URLEncoder.encode(editFile, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		browser1.setUrl("http://localhost:2016/manager/default2.html?editfile="+editFile);
		
		//browser1.setUrl("file:///D:/tools/Workspaces/eclick/src/kindeditor-4.1.10/examples/default.html");
		//}
		
	}
	
	/**
	 * Creates the pages of the multi-page editor.
	 */
	protected void createPages() {
		IFileEditorInput input = (IFileEditorInput)getEditorInput();
		if(!"eclick".equals(input.getFile().getFileExtension())){
			createPage0();
		}
		//createPage1();
		createPage2();
	}
	/**
	 * The <code>MultiPageEditorPart</code> implementation of this 
	 * <code>IWorkbenchPart</code> method disposes all nested editors.
	 * Subclasses may extend.
	 */
	public void dispose() {
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
		super.dispose();
	}
	/**
	 * Saves the multi-page editor's document.
	 */ 
	public void doSave(IProgressMonitor monitor) {
		this.getActiveEditor().doSave(monitor);
		// getEditor(0).doSave(monitor);
	}
	/**
	 * Saves the multi-page editor's document as another file.
	 * Also updates the text for page 0's tab, and updates this multi-page editor's input
	 * to correspond to the nested editor's.
	 */
	public void doSaveAs() {
		IEditorPart editor = getEditor(0);
		editor.doSaveAs();
		setPageText(0, editor.getTitle());
		setInput(editor.getEditorInput());
	}
	/* (non-Javadoc)
	 * Method declared on IEditorPart
	 */
	public void gotoMarker(IMarker marker) {
		setActivePage(0);
		IDE.gotoMarker(getEditor(0), marker);
	}
	/**
	 * The <code>MultiPageEditorExample</code> implementation of this method
	 * checks that the input is an instance of <code>IFileEditorInput</code>.
	 */
	public void init(IEditorSite site, IEditorInput editorInput)
		throws PartInitException {
		if (!(editorInput instanceof IFileEditorInput))
			throw new PartInitException("Invalid Input: Must be IFileEditorInput");
		super.init(site, editorInput);
	}
	/* (non-Javadoc)
	 * Method declared on IEditorPart.
	 */
	public boolean isSaveAsAllowed() {
		return true;
	}
	
	/**
	 * Closes all project files on project close.
	 */
	public void resourceChanged(final IResourceChangeEvent event){
		if(event.getType() == IResourceChangeEvent.PRE_CLOSE){
			Display.getDefault().asyncExec(new Runnable(){
				public void run(){
					IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
					for (int i = 0; i<pages.length; i++){
						if(((FileEditorInput)editor.getEditorInput()).getFile().getProject().equals(event.getResource())){
							IEditorPart editorPart = pages[i].findEditor(editor.getEditorInput());
							pages[i].closeEditor(editorPart,true);
						}
					}
				}            
			});
		}
	}


}
